import {Component, Injector, Input, OnInit, ViewChild} from '@angular/core';
import {_HttpClient} from '@delon/theme';
import {environment} from '@env/environment';
import {UEditorComponent} from 'ngx-ueditor';
import {NewsService} from '../news.service';
import {NEWS, Newsmodle} from '../newsmodle';
import {NzMessageService} from 'ng-zorro-antd';
import {ActivatedRoute, ParamMap} from '@angular/router';
import {MyimguploadComponent} from '@shared/myimgupload/myimgupload.component';
import {Location} from '@angular/common';
import {switchMap} from 'rxjs/operator/switchMap';

@Component({
    selector: 'app-add',
    templateUrl: './add.component.html',
})
export class AddComponent implements OnInit {
    type = null;

    newsmoudle: NEWS = new NEWS();

    @ViewChild('imgload') myuploadimg: MyimguploadComponent;

    constructor(private newsService: NewsService,
                private injector: Injector,
                private activatedRoute: ActivatedRoute,
                private location: Location,
                private msg: NzMessageService,
    ) {
    }


    ngOnInit(): void {
        // this.newsmoudle.type = '1';


        const id = this.activatedRoute.snapshot.paramMap.get('id');
        const type = this.activatedRoute.snapshot.paramMap.get('type');
        if (type !== null) {
            this.type = type;
        }

        if (id) {
            this.newsService.showNewsById(id).subscribe(res => {
                // console.error('res==>' + res);
                this.newsmoudle.id = res['id'];
                this.newsmoudle.title = res['title'];
                this.newsmoudle.subconent = res['subcontent'];
                this.newsmoudle.content = res['conent'];
                this.newsmoudle.cover = res['headimg'];
                this.newsmoudle.type = res['type'];
                this.myuploadimg.setImg(this.newsmoudle.cover);
            });
        }
    }


    save() {
        this.newsService.addNews({
            id: this.newsmoudle.id, title: this.newsmoudle.title,
            content: this.newsmoudle.content, type: this.newsmoudle.type, img: this.newsmoudle.cover,
            subconent: this.newsmoudle.subconent
        }).subscribe(res => {
            this.msg.success('保存成功');
            if (this.type == null) {
                this.location.back();
            }
        }, (e) => {
            console.error(e);
        });
    }


    froalaContent(event) {
        this.newsmoudle.content = event;
    }

    newNews() {
        this.newsmoudle.content = undefined;
        this.newsmoudle.title = undefined;
        this.newsmoudle.subconent = undefined;
        this.newsmoudle.type = 0;
    }


    uploadimg($event) {
        // this.bannerForm.patchValue({
        //     img: $event,
        // });
        this.newsmoudle['cover'] = $event;
    }
}
